<?php
namespace SimpleMVC\lib;

class View {
	
	private $viewPath = '';
	private $vars = array();
	
	public function getViewPath()
	{
		if ($this->viewPath == '') {
			$this->viewPath = APP_PATH . 'view' . DIRECTORY_SEPARATOR;
		}
		return $this->viewPath;
	}
	
	public function setViewPath($path)
	{
		$this->viewPath = $path;
	}
	
	public function assign($key, $val = null)
	{
		if (is_array($key))
		{
			foreach ($key as $k => $v)
			{
				if ($this->_isVar($k)) {
					$this->vars[$k] = $v;
				}
			}
		}
		else
		{
			if ($this->_isVar($key)) {
				$this->vars[$key] = $val;
			}
		}
	}
	
	public function display($view, $return = false)
	{
		if (!$return) {
			header('content-type:text/html;charset=utf-8');
		}
		ob_start();
		extract($this->vars);
		require $this->getViewPath() . $view . '.php';
		if ($return)
		{
			$content = ob_get_contents();
			ob_end_clean();
			return $content;
		}
		else
		{
			ob_end_flush();
		}
	}
	
	protected function _isVar($str)
	{
		return preg_match('/^[a-zA-Z_][0-9a-zA-Z_]*$/', $str) == 1;
	}
}